package com.aplink.generic.xmlparser;

import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.text.TextUtils;

import com.aplink.generic.pojo.formdesign.Column;
import com.aplink.generic.pojo.formdesign.SelectWhere;

public class SelectWhereParser {
    public static final String COLUMN = "column";
    public static final String DEFAULT_VALUE = "defaultValue";
    public static final String OBJECT_LOAD_BY = "selectWhere";
    public static final String PASSED_COLUMN_ID = "passedColumnID";
    public static final String TARGET = "target";
    public static final String TARGETS = "targets";

    public static SelectWhere parsse(Node node) {
        final SelectWhere objectLoadBy = new SelectWhere();
        Element element = (Element) node;
        NodeList nodes = element
                .getElementsByTagName(SelectWhereParser.OBJECT_LOAD_BY);
        if (nodes.getLength() == 0) {
            return objectLoadBy;
        }
        node = nodes.item(0);
        if (node.hasAttributes()) {
            final String target = XMLPaserUtil.getAttrValue(node,
                    SelectWhereParser.TARGET);
            if (!TextUtils.isEmpty(target)) {
                objectLoadBy.setTargetClass(target);
            }
        }
        if (node.getNodeType() == Node.ELEMENT_NODE) {
            element = (Element) node;
            nodes = element.getElementsByTagName(SelectWhereParser.COLUMN);
            for (int i = 0; i < nodes.getLength(); i++) {
                final Column column = new Column();
                final Node nodeColumn = nodes.item(i);
                String defaultValue = null;
                if (nodeColumn.hasAttributes()) {
                    defaultValue = XMLPaserUtil.getAttrValue(nodeColumn,
                            SelectWhereParser.DEFAULT_VALUE);
                    column.setDefaultValue(defaultValue);
                    defaultValue = XMLPaserUtil.getAttrValue(nodeColumn,
                            SelectWhereParser.PASSED_COLUMN_ID);
                    column.setPassedColumnID(defaultValue);

                }
                final String columnValue = XMLPaserUtil
                        .getNodeValue(nodeColumn);
                column.setColumnName(columnValue);
                objectLoadBy.add(column);
            }
        }
        return objectLoadBy;
    }
}
